
import 'package:eshi/app/shi/data/Config.dart';
import 'package:eshi/app/shi/data/HistoryMarks.dart';
import 'package:eshi/app/shi/data/System.dart';
import 'package:eshi/app/shi/taxis/TabEditPageMarkEdit.dart';
import 'package:eshi/app/shi/taxis/tab_edit_page/tab_edit_page_action.dart';
import 'package:eshi/app/shi/taxis/tab_edit_page/tab_edit_page_event.dart';
import 'package:eshi/app/shi/widget/CommonWidgets.dart';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:eshi/app/CommonFunctions.dart';

/// tab项编辑界面 
class TabEditPage  extends StatefulWidget{
  String title;
  bool titleCanEdit;
  String data;
  Function(String data,Map<String,List<String>> marks,String title) onChange;
  Widget? tools;
  Map<String,List<String>>? marks;
  bool isWrapText = Config.editPageisWrapText;
  final String? hintText=null;
  final int tabSpaces=8;
  final TextStyle textStyle=const TextStyle(
                  fontSize: 14,
                  height: 1.5,
                );
  final TextStyle? lineNumberStyle=null;
  final EdgeInsetsGeometry padding =const EdgeInsets.symmetric(vertical: 10,horizontal: 5);

  TabEditPage({required this.title,required this.data,this.tools,this.titleCanEdit=false,this.marks,required this.onChange,super.key}){
    if(title.isEmpty){
      title="新增";
      titleCanEdit = true;
    }
  }

  @override
  State<StatefulWidget> createState() => TabEditPageState();
}
//视图
class TabEditPageState extends State<TabEditPage> with  TabEditPageEvent,TabEditPageAction{
  TextEditingController controller = TextEditingController();
  //TextStyle _currentStyle = TextStyle();
  final GlobalKey textFieldKey = GlobalKey(); // 用于获取TextField宽度
  final ScrollController _textScrollController = ScrollController();
  final ScrollController _lineNumbersScrollController = ScrollController();
  final ScrollController _verticalController = ScrollController(); // 垂直滚动控制器
  final ScrollController _horizontalController = ScrollController(); // 水平滚动控制器

  @override
  void initState() {
    super.initState();
    controller.text = widget.data;
    // 监听内容变化，更新行号
    controller.addListener(updateLineNumbers);
    updateLineNumbers();
    double scrollPos = 0;
    // _titleTextController.text = ""
    // 同步两个滚动控制器
    _textScrollController.addListener(() {
      _lineNumbersScrollController.jumpTo(_textScrollController.offset);
      scrollPos = _textScrollController.offset;
        print("dpos:${_lineNumbersScrollController.offset}");
    });
    _verticalController.addListener(() {
      _lineNumbersScrollController.jumpTo(_verticalController.offset);
       scrollPos = _textScrollController.offset;
       print("vpos:${_lineNumbersScrollController.offset}");
    });
    _lineNumbersScrollController.addListener((){
      print("pos:${_lineNumbersScrollController.offset}");
      if(scrollPos.toInt() != _lineNumbersScrollController.offset.toInt()){
          _lineNumbersScrollController.jumpTo( scrollPos);
      }
    });
    //软键盘状态修改之后刷新页面
    System.onKeyboardOpenedChange(run:() => setState(() {}));
  }

  @override
  void dispose() {
    // 如果是内部创建的控制器，需要手动释放
    controller.dispose();
    _textScrollController.dispose();
    _lineNumbersScrollController.dispose();
    super.dispose();
  }
  int lineCount = 1;
  int cursorLine = 0;
  int cursorCol = 0;
  int cursorLevel = 0;
  List<int> cursorLines = [0];
 
  Map<String,List<String>> marksGroup ={};
  List<XFile> importFiles =[];
  bool get isWrapText{
    return widget.isWrapText;
  }
  final titleTextController = TextEditingController();
    // 记录键盘是否弹出
  bool isKeyboardVisible = false;
  //标签
  Widget marksRemove(){
    if(widget.marks==null || widget.marks!.isEmpty) return SizedBox(height: 1);
    final marks = widget.marks!.map((k,List<String> v){
      var name = HistoryMarks.byName(k).title;
      return MapEntry(name,v.where((w) => widget.data.contains(w) ));
    });
    return Column(children: [
      for(final m in marks.entries)
        if(m.value.isNotEmpty)
        Row(
         crossAxisAlignment: CrossAxisAlignment.start,
         children: [
          Padding(
            // 四周统一内边距（上下左右各 8 像素）
            padding: const EdgeInsets.only(top:1.0),
            child: Text("${m.key}:"),
          ),
          Expanded(
          child:  Wrap(
             // 对齐方式（左对齐、居中、右对齐等）
            alignment: WrapAlignment.start,
            // 主轴方向的间距（水平方向）
            spacing: 8.0,
            // 交叉轴方向的间距（垂直方向，换行后的行间距）
            runSpacing: 1.0,
            children: [
              for(final v in m.value)
              InkWell(
                  child: mText(v),  
                   // 通过 style 修改内边距
                  onTap: () {
                  widget.marks![m.key]!.remove(v);
                  if(!marksGroup.containsKey("delete")) marksGroup["delete"] = [];
                  marksGroup["delete"]!.add(v);
                  setState(() {
                    
                  });
                })
            ]
          )
        )
        ])
    ]);
  }
  
  //标题
  Widget titleEdit(){
     return Container(
      padding: EdgeInsets.only(bottom: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
            SizedBox(width: 28, child: Container(color: Colors.grey[50])),
            Expanded(child: 
              TextFormField(
                      controller: titleTextController, // 必须指定controller
                      decoration:  InputDecoration(
                        labelText: mt("标题"),
                        hintText: mt("请输入标题"),
                        border: OutlineInputBorder(),
                        
                      ),
                      
                      // maxLength: 50, // 限制标题长度
                      validator: (value) {
                        if (value == null || value.trim().isEmpty) {
                          return mt("请输入标题");
                        }
                        return null;
                      },
              )
            ),
            //  SizedBox(width: 28, child: Container(color: Colors.grey[50])),
        ]
      )
    );
  }
  // 构建行号列表
  Widget _buildLineNumbers() {
     return Padding(
      padding: EdgeInsets.only(top:2),
      child:Container(
        width: 28,
        padding: widget.padding,
        // color: widget.docToolsColor,
        child: ListView.builder(
          controller: _lineNumbersScrollController,
          itemCount: lineCount,
          physics: const NeverScrollableScrollPhysics(), // 禁止独立滚动
          itemBuilder: (context, index) =>Column(children: [Text(
            '${index + 1}',
            style: TextStyle(
              color: cursorLines.contains(index) ? Colors.blue: Colors.grey[500],
              fontSize: 14,
              height: 1.5,
              fontFamily: 'monospace',
            ),
          ),
          if(isWrapText && docLinesCountMap.containsKey(index))
            SizedBox(height: 14*1.5*(docLinesCountMap[index]-1))
          ]),
        ),
      ));
  }
  //四面拖拽的盒子
  Widget scrollBox({required Widget child,double height=0}){

    // 外层：垂直滚动条 + 垂直滚动容器
      return Container(
        decoration: BoxDecoration(
            border: Border.all(color: Colors.blueGrey,width: 2.0),
            borderRadius:BorderRadius.all(Radius.circular(4.0))
         ),
        child:  Scrollbar(
            controller: _verticalController,
            // thumbVisibility: true, // 始终显示垂直滚动条
            thickness: 6,
            radius: const Radius.circular(3),
            child: SingleChildScrollView(
              controller: _verticalController,
              scrollDirection: Axis.vertical, // 垂直方向滚动
              child: SizedBox(
                // 限制宽度，确保水平滚动生效
                width: MediaQuery.of(context).size.width - 28, // 减去左右padding
                child: Scrollbar(
                  controller: _horizontalController,
                  thumbVisibility: true, // 始终显示水平滚动条
                  thickness: 6,
                  radius: const Radius.circular(3),
                  notificationPredicate: (notification) => notification.depth == 1, // 只响应水平滚动事件
                  child: SingleChildScrollView(
                    controller: _horizontalController,
                    scrollDirection: Axis.horizontal, // 水平方向滚动
                    child: SizedBox(
                      // 限制高度，避免TextField无限增高
                      height: height >0 ? height :  MediaQuery.of(context).size.height/3*2,
                      child: child
                    ),
                  ),
                ),
              )
            )
          ));
  }
    
  get _normalStyle => widget.textStyle;
  late final TextStyle _commentStyle = _normalStyle.copyWith(
    color: Colors.green,
    fontStyle: FontStyle.italic,
  );
  // 构建富文本样式的文本Span（用于显示）
  TextSpan _buildTextSpan() {
    final text = controller.text;
    final lines = text.split('\n');
    final children = <TextSpan>[];

    for (var i = 0; i < lines.length; i++) {
      final line = lines[i];
      final trimmedLine = line.trimLeft();
      
      // 处理注释（//开头的内容）
      if (trimmedLine.startsWith('//')) {
        final indentLength = line.length - trimmedLine.length;
        // 添加缩进部分
        if (indentLength > 0) {
          children.add(TextSpan(
            text: line.substring(0, indentLength),
            style: _normalStyle
          ));
        }
        // 添加注释部分
        children.add(TextSpan(
          text: line.substring(indentLength),
          style: _commentStyle
        ));
      } else {
        // 处理行内注释
        final commentIndex = line.indexOf('//');
        if (commentIndex != -1) {
          // 正常文本部分
          children.add(TextSpan(
            text: line.substring(0, commentIndex),
            style: _normalStyle
          ));
          // 行内注释部分
          children.add(TextSpan(
            text: line.substring(commentIndex),
            style: _commentStyle
          ));
        } else {
          // 纯正常文本
          children.add(TextSpan(
            text: line,
            style: _normalStyle
          ));
        }
      }
      
      // 添加换行符（最后一行除外）
      if (i != lines.length - 1) {
        children.add(const TextSpan(text: '\n'));
      }
    }

    return TextSpan(children: children);
  }
  late FocusNode _focusNode = FocusNode();
  //文本框
  Widget docText1(){
    return Stack(
                children: [
                  // 1. 富文本显示层（用于颜色区分）
                  Positioned.fill(
                    child: SingleChildScrollView(
                      controller: isWrapText? _textScrollController :null,
                      child: Padding(
                        // 匹配输入框的内边距，确保视觉对齐
                        padding: const EdgeInsets.symmetric(
                          horizontal: 11,
                          vertical: 10,
                        ),
                        child: RichText(
                          text: _buildTextSpan(),
                        ),
                      ),
                    ),
                  ),
                  // 2. 透明输入层（用于编辑功能）
                  // docText0()
                ],
              );
  }
  Widget docText(){
    return TextField(
          key:textFieldKey,
          controller: controller,
          scrollController: isWrapText? _textScrollController :null,
          scrollPhysics:  isWrapText? const AlwaysScrollableScrollPhysics() : null,
          keyboardType: TextInputType.multiline,
          maxLines: null,
          minLines: null,
          showCursor:true,
          // 核心2：允许水平滚动
          expands: true, // 配合Expanded占满高度
          // 禁用自动换行（关键：通过textInputAction控制换行）
          textInputAction: TextInputAction.newline, // 回车时换行
          // 关键配置：禁止自动换行
          // softWrap: false,   // 关闭自动换行（虽然TextField没有此属性，但传递给内部组件）
          // buildCounter: (
          //   BuildContext context, {
          //   required int currentLength,
          //   required int? maxLength,
          //   required bool isFocused,
          // }) {
          //      return docCounter(currentLength);
          // },
          textAlignVertical: TextAlignVertical.top, // 文本顶部对齐
          style: widget.textStyle,
          decoration: InputDecoration(
            hintText: widget.hintText ?? '${mt("开始输入")}...',
            labelText: isWrapText ?  mt("内容") :null,
            border: isWrapText ?  OutlineInputBorder() :null,
            contentPadding: widget.padding,
            alignLabelWithHint: true, // 多行输入时标签对齐提示文字
            isDense: true,
          ),
        );
  }
  Widget _toolsButton({required Widget icon,required Function onPressed,GestureLongPressCallback? onLongPress}){
     return SizedBox(
        width: 28,
        height: 28,
        child:   InkWell(
            borderRadius: BorderRadius.circular(8), // 水波纹圆角
            splashColor: Colors.blue,
            onTap: () => onPressed(),
            onLongPress: onLongPress, // 水波纹颜色
            child: icon,
        )
      );
  }
  //手机端虚拟按键 
  Widget docCounter(currentLength){
     return SizedBox(
                  // padding: const EdgeInsets.only(top: 1.0),
                  height: 30,
                  // color: widget.docToolsColor,
                  child: Row(
                    // 主轴方向的间距（水平方向）
                    // spacing: 8.0,
                    children: [
                      if(System.isKeyboardOpened)
                        Wrap(
                            alignment: WrapAlignment.start,
                            runSpacing:0,
                            children: [
                              _toolsButton( //tab
                                icon:Icon(Icons.format_indent_increase)
                                // icon:Icon(Icons.keyboard_double_arrow_right_rounded)
                              ,onPressed:(){
                                  sendKeyEvent(
                                    logicalKey: LogicalKeyboardKey.tab,
                                    physicalKey: PhysicalKeyboardKey.tab,
                                  );
                              }),
                              _toolsButton( //shift+tab
                                onPressed: (){
                                  sendKeyEventWithModifiers(
                                    logicalKey: LogicalKeyboardKey.tab,
                                    physicalKey: PhysicalKeyboardKey.tab,
                                    withShift: true,
                                  );
                                },
                                icon: Icon(Icons.format_indent_decrease)
                              ),
                              // },icon: Icon(Icons.keyboard_double_arrow_left_rounded)),
                              //annotate,
                              _toolsButton( //注释 ctrl+//
                                onPressed: (){
                                  sendKeyEventWithModifiers(
                                    logicalKey: LogicalKeyboardKey.slash,
                                    physicalKey: PhysicalKeyboardKey.slash,
                                    withCtrl: true,
                                  );
                                },
                                icon: Icon(Icons.numbers_rounded)
                              ),
                              _toolsButton( //行删除 dd
                                icon:  Icon(Icons.strikethrough_s),
                                onPressed: (){
                                delLine();
                              }),
                              // _toolsButton( //撤销 ctrl+z
                              //   onPressed: (){
                              //      sendKeyEventWithModifiers(
                              //       logicalKey: LogicalKeyboardKey.keyZ,
                              //       physicalKey: PhysicalKeyboardKey.keyZ,
                              //       withCtrl: true,
                              //     );
                              //   },
                              //   onLongPress: (){
                              //     int i=0;
                              //     while(i++<100)
                              //     sendKeyEventWithModifiers(
                              //       logicalKey: LogicalKeyboardKey.keyZ,
                              //       physicalKey: PhysicalKeyboardKey.keyZ,
                              //       withCtrl: true,
                              //     );
                              // },icon: Icon(Icons.replay)),

                              // _toolsButton(  //反撤销 ctrl+shift+z
                              //  onPressed: (){
                              //     _sendKeyEventWithModifiers(
                              //       logicalKey: LogicalKeyboardKey.keyZ,
                              //       physicalKey: PhysicalKeyboardKey.keyZ,
                              //       withCtrl: true,
                              //       withShift: true,
                              //     );
                              //  },
                              //  icon: Icon(Icons.refresh)
                              // ),


                              _toolsButton( //行首 home
                                icon:  Icon(Icons.keyboard_arrow_left),
                                onPressed: (){
                                  toLineStart();
                                }
                              ),
                             _toolsButton( //行尾 end
                                icon:  Icon(Icons.keyboard_arrow_right),
                                onPressed: (){
                                  toLineEnd();
                              }),
                              _toolsButton( //自动换行
                                icon: isWrapText ? Icon(Icons.wrap_text,color:Colors.blue): Icon(Icons.wrap_text),
                                onPressed: (){
                                  setState(() {
                                    widget.isWrapText = !isWrapText;  
                                    Config.editPageisWrapText = isWrapText;
                                    updateLineNumbers();
                                    setState(() {});
                                  });
                              }),
                            ]
                        ),
                      Expanded(child: SizedBox()),  
                      Text("$cursorLevel,${cursorLines[0]+1},$cursorCol ",style: TextStyle(color: Colors.grey,fontSize: 12)),
                      Text(" $currentLength",style: TextStyle(color: Colors.grey,fontSize: 12)),
                    ]
                  )
                );
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
     return Scaffold(
       resizeToAvoidBottomInset: false,
       appBar: AppBar( 
         // backgroundColor: Colors.lightGreen,
         title:  Text(widget.title),
         actions: [
              InkWell(
               child: Icon(Icons.link),
                 // tooltip:mt("文件引用"),
                 onLongPress: () async {
                   await simpleDialog(context: context, 
                     body: MarkEdit(this),
                     scrollable: true,
                     barrierDismissible: false,
                   );
                 },
                 // onDoubleTap: () {
                 //    onLoadFile();
                 // },
                 onTap: () async{
                    onLoadFile();
                   //  tmpTcMap
                 }
              ),
              SizedBox(width: 10,),
              ElevatedButton(
                 child: mText("保存"),
                 onPressed: () {
                    onSave();
                 }
               ),
               SizedBox(width: 10,)
         ],
       ),
       body:Form(
         child: Container( 
           padding: EdgeInsets.fromLTRB(2, 10, 10, 10),
           child:  Column(children: [
             //附加的工具 
             if(widget.tools!=null)
               Align(
                 alignment: Alignment.topLeft,
                 child:   widget.tools!
               ),
             //标题框
             if(widget.titleCanEdit)
               titleEdit(),
             //内容框
             Expanded(child:Row(
               crossAxisAlignment: CrossAxisAlignment.start,
               children: [
                 // 行号列
                 _buildLineNumbers(),
                 // 文本输入区域
                 Expanded(
                   child: Focus(
                     onKey:(node,RawKeyEvent event) {
                       if(event is RawKeyDownEvent){
                         return onKeyDown(event);
                       }
                       return KeyEventResult.ignored;
                     },
                     child: LayoutBuilder(builder: (context, constraints) {
                       // constraints.maxHeight 就是Expanded分配的高度
                       final expandedHeight = constraints.maxHeight-40;
                       return Column(
                         children: [
                           SizedBox(
                             height: expandedHeight,
                             child: isWrapText ? docText() : scrollBox(
                               height: expandedHeight,
                               child: SizedBox(width: maxLineWidth,child:docText())
                           )),
                           docCounter(controller.text.length)
                         ]
                       );
                     }),
                   ),
                 ),
               ],
             )),
             if(!System.isKeyboardOpened)
               marksRemove()
         ]
       )))
     );
  }
}
